﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;

namespace ProjManagSolution
{
    public class UploadManager
    {
        public string StartSelectFileAndUpload(int projectID)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Multiselect = false;
            ofd.Filter = "Word file (*.doc)|*.doc|PDF file (*.pdf)|*.pdf";

            bool? retval = ofd.ShowDialog();

            if (retval != null && retval == true)
            {
                UploadFile(ofd.File.Name, ofd.File.OpenRead() , projectID);
            }

            return ofd.File.Name;
        }

        private void UploadFile(string fileName, Stream data , int projectID)
        {
            ////Get Project ID to create folder
            //Session s = new Session();
            //string projectID = s.GetProjectInfo().project_id.ToString();

            UriBuilder ub = new UriBuilder("http://localhost:1234/receiver.ashx");
            ub.Query = string.Format("filename={0}&projectid={1}", fileName, projectID);

            WebClient c = new WebClient();
            c.OpenWriteCompleted += (sender, e) =>
            {
                PushData(data, e.Result);
                e.Result.Close();
                data.Close();
            };
            c.OpenWriteAsync(ub.Uri);
        }

        private void PushData(Stream input, Stream output)
        {
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }
    }
}
